//----------------------------------Include-------------------------------------
#include <stdint.h>
#include "mcu.h"
#include "glbvar.h"
//------------------------------------------------------------------------------

//-----------------------------------Macro--------------------------------------
#define _TIM       (TIM3)
#define _IRQ       (TIM3_IRQn)
//------------------------------------------------------------------------------

//--------------------------------Static Var------------------------------------
static uint32_t    src_clk;
static uint32_t    clk_div;
static uint32_t    req_freqHz;
static uint32_t    period_cnt;
//------------------------------------------------------------------------------

//--------------------------------Public Func-----------------------------------
void mcu_init_tim3(void)
{
//periph clock
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
  
//timer base
  src_clk    = mcu_get_timclk();
  clk_div    = 120;
  req_freqHz = 1000;       //Hz
  period_cnt = (src_clk/clk_div)/req_freqHz;
  
  TIM_TimeBaseInitTypeDef   TIM_TimeBase;
  TIM_TimeBaseStructInit   (&TIM_TimeBase);
  
  TIM_TimeBase.TIM_Prescaler     = clk_div -1;      //TIMx->PSC  1~65536
  TIM_TimeBase.TIM_CounterMode   = TIM_CounterMode_Up;
  TIM_TimeBase.TIM_Period        = period_cnt -1;   //TIMx->ARR  1~65536
  TIM_TimeBase.TIM_ClockDivision = TIM_CKD_DIV1;
  TIM_TimeBaseInit(_TIM, &TIM_TimeBase);
  
//interrupt
  TIM_ITConfig(_TIM, TIM_IT_Update, ENABLE);
  
//NVIC
  NVIC_InitTypeDef    NVIC_InitS;
  
  NVIC_InitS.NVIC_IRQChannel         = _IRQ;
  NVIC_InitS.NVIC_IRQChannelPriority = 0;
  NVIC_InitS.NVIC_IRQChannelCmd      = ENABLE;
  NVIC_Init(&NVIC_InitS);
  
//enable
  TIM_Cmd(_TIM, ENABLE);
}
//------------------------------------------------------------------------------

//------------------------------------ISR---------------------------------------
void TIM3_IRQHandler(void)
{
  if(_TIM->SR &  (1<<0)){
    _TIM->SR &= ~(1<<0);
    
#if 1
  igu64_tick_ms++;
  
  static unsigned int cnt;
  if(++cnt >= 1000){
    cnt = 0;
    mcu_led_toggle();
  }
#endif
  }
  
  if(_TIM->SR){
    _TIM->SR = 0;
  }
}
//------------------------------------EOF---------------------------------------









